/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package apteka.admin;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;

/**
 *
 * @author Marek
 */
public class ImageResizer {


    public ImageResizer() {

    }

    public void resizeFile(File file,int width) {
        try {
            Image image = ImageIO.read(file);
            int height = (int)(((float)width/(float)image.getWidth(null))*image.getHeight(null));
            BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = thumbImage.createGraphics();
            graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics2D.drawImage(image, 0, 0, width, height, null);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
            int quality = 100; // Use between 1 and 100, with 100 being highest quality
            quality = Math.max(0, Math.min(quality, 100));
            param.setQuality((float)quality / 100.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(thumbImage);
            ImageIO.write(thumbImage, "IMAGE_JPG" , out);
            OutputStream outputStream = new FileOutputStream (file.getAbsolutePath());
            out.writeTo(outputStream);
            outputStream.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

}
